package io.renren.modules.cw.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import io.renren.common.utils.EasyExcelUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.cw.entity.InvoiceEntity;
import io.renren.modules.cw.service.InvoiceService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;

import static io.renren.common.utils.ShiroUtils.getUserId;


/**
 * 
 *
 * @author luowenlu
 * @email luowenlu@163.com
 * @date 2023-03-26 07:46:08
 */
@RestController
@RequestMapping("cw/invoice")
public class InvoiceController {
    @Autowired
    private InvoiceService invoiceService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("cw:invoice:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = invoiceService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("cw:invoice:info")
    public R info(@PathVariable("id") Integer id){
		InvoiceEntity invoice = invoiceService.getById(id);

        return R.ok().put("invoice", invoice);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("cw:invoice:save")
    public R save(@RequestBody InvoiceEntity invoice){
        String userId = getUserId().toString();
        invoice.setCreatedBy(userId);
        invoice.setCreatedAt(new Date());
        invoiceService.save(invoice);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("cw:invoice:update")
    public R update(@RequestBody InvoiceEntity invoice){
		invoiceService.updateById(invoice);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("cw:invoice:delete")
    public R delete(@RequestBody Integer[] ids){
		invoiceService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    @PostMapping ("/readFromExcel")
    public R importSave(@RequestParam("file") MultipartFile file) {
        try {
            InputStream excelFileInputStream = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后默认读取第一个sheet 文件流会自动关闭
            // 直接new了监听器，lambda表达式进行数据后续处理
            EasyExcel.read(excelFileInputStream, InvoiceEntity.class, new PageReadListener<InvoiceEntity>(dataList -> {
                for (InvoiceEntity invoice : dataList) {
                    String userId = getUserId().toString();
                    invoice.setCreatedBy(userId);
                    invoice.setCreatedAt(new Date());
                    invoiceService.save(invoice);
                }


            })).sheet().doRead();//sheet()可指定读取哪一个sheet，支持名字和索引，索引起始为0
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }



    @PostMapping ("/exportExcel")
    public void exportExcel(@RequestBody InvoiceEntity invoice, HttpServletResponse response) {
        List<InvoiceEntity> list = invoiceService.list();
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            //"测试"：就是我们要生成文档的名称，可以改为自己的
            String fileName = URLEncoder.encode("发票表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(),InvoiceEntity.class).autoCloseStream(Boolean.FALSE).sheet().doWrite(list);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }



}
